package com.xcity.game.http;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.xcity.db.entity.Mail;
import com.xcity.db.entity.Player;
import com.xcity.db.entity.User;
import com.xcity.game.account.AccountService;
import com.xcity.game.activity2.share.action.WeiboShareAction;
import com.xcity.game.event.GameEvents;
import com.xcity.game.http.gm.GMService;
import com.xcity.game.http.impl.GMReward;
import com.xcity.game.http.impl.GMReward.GMRewardItem;
import com.xcity.game.mail.MailAttach;
import com.xcity.game.mail.MailService;
import com.xcity.game.player.PlayerService;
import com.xcity.game.recharge.RechargeServlet;
import com.xcity.pomelo.PomeloRoute;
import com.xcity.pomelo.push.msg.TipPush;
import com.xcity.pomelo.request.ShareGameRequest;
import com.xcity.pomelo.response.HintResponse;
import com.xcity.pomelo.response.Response;

import naga.x.App;
import naga.x.event.Event;
import naga.x.event.EventListener;
import naga.x.net.Session;
import naga.x.net.annotation.OPHandler;
import naga.x.net.impl.pomelo.annotation.PomeloOP;
import naga.x.service.Service;
import naga.x.service.ServiceException;
import naga.x.util.StringUtils;

@OPHandler
public class HttpService implements Service, EventListener {

	protected static final Logger LOG = LoggerFactory.getLogger(HttpService.class);
	
	protected Map<String, GMReward> gmRewards = new ConcurrentHashMap<String, GMReward>();
	
	@Override
	public void startup() throws ServiceException {
//		Server jetty = new Server(new InetSocketAddress("0.0.0.0", App.getApp().getConfig().getIntValue(Config.HTTP_PORT)));
		Server jetty = new Server(new InetSocketAddress("0.0.0.0", App.getApp().getConfig().httpPort));
		ServletContextHandler handler = new ServletContextHandler();
		handler.setContextPath("/");
		handler.addServlet(new ServletHolder(new RechargeServlet()), "/recharge");
		GMService gmService = App.getApp().getServiceManager().create(GMService.class);
		handler.addServlet(new ServletHolder(new GMServlet(gmService)), "/xgm");
		jetty.setHandler(handler);
		try {
			jetty.start();
		} catch (Exception e) {
			LOG.error("[JETTY START FAILED]", e);
			System.exit(1);
		}
		App.getApp().getEventManager().register(this);
	}

	@Override
	public void shutdown() throws ServiceException {
	}

	@Override
	public String getId() {
		return getClass().getName();
	}
	
	public void offerReward(GMReward reward) {
		gmRewards.put(reward.getUid(), reward);
		doReward(reward);
		User acc = App.getApp().getServiceManager().get(AccountService.class).find(reward.getUid());
		if (acc != null) {
			long pid = acc.getDefaultPlayerId();
			Player player = App.getApp().getServiceManager().get(PlayerService.class).getOnlinePlayer(pid);
			if (player != null) {
				playerLogin(player);
			}
		}
	}

	@Override
	public int[] getEventTypes() {
		return new int[] { GameEvents.EVENT_PLAYER_LOGIN };
	}

	@Override
	public void handleEvent(Event event) {
		switch (event.getType()) {
			case GameEvents.EVENT_PLAYER_LOGIN:
				playerLogin(event.getParameter());
				break;
		}
	}
	
	protected void playerLogin(Player player) {
		User acc = player.getAccount();
		String uid = acc.getChannelUid();
		GMReward reward = gmRewards.remove(uid);
		if (reward != null && StringUtils.isNotEmpty(reward.getMsg())) {
			player.send(new TipPush(reward.getMsg()));
		}
	}
	
	private void doReward(GMReward reward) {
		User acc = App.getApp().getServiceManager().get(AccountService.class).find(reward.getUid());
		long pid = acc.getDefaultPlayerId();
		Mail mail = new Mail(Mail.TYPE_SYSTEM, -1, pid, reward.getMailTitle(), reward.getMailContent());
		mail.setAttachment(new MailAttach());
		if (reward.getGold() > 0) {
			mail.getAttachment().setGold(reward.getGold());
		}
		if (reward.getStone() > 0) {
			mail.getAttachment().setStone(reward.getStone());
		}
		if (reward.getItems() != null && reward.getItems().size() > 0) {
			for (GMRewardItem item : reward.getItems()) {
				mail.getAttachment().addItem(item.getId(), item.getCount());
			}
		}
		App.getApp().getServiceManager().get(MailService.class).sendMail(mail);
		LOG.info("[GM REWARD]ID[{}]REWARD[{}]", pid, JSON.toJSONString(reward));
	}
	
	@PomeloOP(PomeloRoute.SHARE_GAME)
	protected void requestShare(Session session, ShareGameRequest req) {
		Player player = session.getClient();
		String error = WeiboShareAction.doShare(player, req.getToken(), req.getStatus(), req.getRip());
		if (error != null) {
			session.send(new HintResponse(req.getSerial(), error));
			return;
		}
		session.send(new Response(req.getSerial()));
	}

}
